package com.peacock.feather.utility;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;


/**
 * javamail工具类
 * 
 * @author 项硕
 */
public class XMailUtils {

	/**
	 * 发送邮件，需要权限认证
	 * @param host
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 * @param username
	 * @param pwd
	 * @throws MessagingException
	 */
	public static void send(
			String host, String from, String to, String subject, String content, 
			final String username, final String pwd) throws MessagingException {
		Properties props = new Properties();
		props.put("mail.smtp.host", host);	// 设置邮件服务器
		
		boolean isAuthorized = StringUtils.isNotBlank(username) && StringUtils.isNotBlank(pwd);	// 是否权限认证
		Authenticator au = null;
		if (isAuthorized) {
			props.setProperty("mail.smtp.auth", "true");	
			au = new Authenticator() {
				
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, pwd);
				}
			};
		}
		Session session = Session.getInstance(props, au);
		
		try {
		    MimeMessage msg = new MimeMessage(session);
		    msg.setFrom(new InternetAddress(from));
		    InternetAddress[] address = {new InternetAddress(to)};
		    msg.setRecipients(Message.RecipientType.TO, address);
		    msg.setSubject(subject);
		    msg.setSentDate(new Date());
		    msg.setText(content);
		    
		    Transport.send(msg);
		} catch (MessagingException e) {
		    e.printStackTrace();
		    throw e;
		}
	}
	
	/**
	 * 发送邮件
	 * @param host
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 * @throws MessagingException
	 */
	public static void send(String host, String from, String to, String subject, String content) 
			throws MessagingException {
		send(host, from, to, subject, content, null, null);
	}

	/* ---------------------------------------- test ---------------------------------------- */
	
	@Test
	public void testSend() {
		String host = "smtp.163.com";
		String from = "m13661927770@163.com";
		String to = "m13661927770@gmail.com";
		String subject = "测试主题";
		String content = "测试内容";
		String username = "m13661927770@163.com";
		String pwd = "815815x";
		
		try {
			XMailUtils.send(host, from, to, subject, content, username, pwd);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}
